import React, { useState, useEffect } from 'react';
import { useParams, Link } from 'react-router-dom';
import { Play, Filter, Search, MoreVertical, GitBranch, Calendar, FileCode } from 'lucide-react';
import { TASKS, getRecordsByTask, triggerScan } from '../services/mockService';
import { ScanStatusBadge } from '../components/StatusBadge';
import { ScanRecord, ScanStatus } from '../types';

export const ScanTaskPage: React.FC = () => {
  const { taskId } = useParams<{ taskId: string }>();
  const [task, setTask] = useState(TASKS[0]);
  const [records, setRecords] = useState<ScanRecord[]>([]);
  const [isScanning, setIsScanning] = useState(false);
  const [selectedBranch, setSelectedBranch] = useState('develop');

  useEffect(() => {
    const t = TASKS.find(t => t.id === taskId);
    if (t) {
      setTask(t);
      setRecords(getRecordsByTask(t.id));
    }
  }, [taskId]);

  const handleScan = async () => {
    setIsScanning(true);
    // Optimistic UI update or wait for "start"
    const newRecord = await triggerScan(task.id, selectedBranch);
    setRecords([newRecord, ...records]);
    
    // Simulate scan finish after 3 seconds
    setTimeout(() => {
        setRecords(prev => prev.map(r => r.id === newRecord.id ? {
            ...r, 
            status: ScanStatus.COMPLETED, 
            duration: '3.2s',
            totalIssues: 15,
            unconfirmedIssues: 15,
            confirmedIssues: 0
        } : r));
        setIsScanning(false);
    }, 3000);
  };

  return (
    <div className="space-y-8">
      {/* Header Section */}
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
          <h1 className="text-3xl font-bold text-slate-900 tracking-tight">{task.name}</h1>
          <p className="text-slate-500 mt-2 max-w-2xl">{task.description}</p>
        </div>
        <div className="flex items-center gap-3 bg-white p-2 rounded-xl shadow-sm border border-slate-100">
          <div className="relative">
             <GitBranch className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
             <select 
                value={selectedBranch}
                onChange={(e) => setSelectedBranch(e.target.value)}
                className="pl-9 pr-4 py-2 bg-slate-50 border-none rounded-lg text-sm font-medium text-slate-700 focus:ring-2 focus:ring-indigo-500/20 outline-none appearance-none cursor-pointer hover:bg-slate-100 transition-colors"
             >
                <option value="develop">develop</option>
                <option value="master">master</option>
                <option value="feature/auth">feature/auth</option>
             </select>
          </div>
          <button 
            onClick={handleScan}
            disabled={isScanning}
            className={`flex items-center gap-2 px-6 py-2.5 rounded-lg text-sm font-semibold text-white transition-all shadow-lg shadow-indigo-500/30 hover:shadow-indigo-500/40 active:scale-95 ${isScanning ? 'bg-indigo-400 cursor-not-allowed' : 'bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-500 hover:to-purple-500'}`}
          >
            {isScanning ? (
                <>Scanning...</>
            ) : (
                <>
                    <Play className="w-4 h-4 fill-current" />
                    One-Click Scan
                </>
            )}
          </button>
        </div>
      </div>

      {/* Active Scan Progress (Visual only if running) */}
      {isScanning && (
         <div className="w-full bg-indigo-50 rounded-lg p-4 border border-indigo-100 animate-pulse flex items-center gap-4">
             <div className="w-6 h-6 border-2 border-indigo-600 border-t-transparent rounded-full animate-spin"></div>
             <div className="flex-1">
                 <p className="text-sm font-medium text-indigo-900">Scanning branch <b>{selectedBranch}</b>...</p>
                 <div className="w-full bg-indigo-200 h-1.5 rounded-full mt-2 overflow-hidden">
                    <div className="h-full bg-indigo-600 animate-[loading_2s_ease-in-out_infinite] w-1/2"></div>
                 </div>
             </div>
         </div>
      )}

      {/* Filters */}
      <div className="flex items-center justify-between">
          <h2 className="text-lg font-bold text-slate-800">Scan History</h2>
          <div className="flex items-center gap-2">
              <div className="relative group">
                 <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400 group-focus-within:text-indigo-500 transition-colors" />
                 <input 
                   type="text" 
                   placeholder="Search branch..." 
                   className="pl-9 pr-4 py-2 bg-white border border-slate-200 rounded-lg text-sm text-slate-600 focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 w-64 transition-all"
                 />
              </div>
              <button className="p-2 bg-white border border-slate-200 rounded-lg text-slate-600 hover:bg-slate-50 hover:text-indigo-600 transition-colors">
                  <Filter className="w-4 h-4" />
              </button>
          </div>
      </div>

      {/* Records Table */}
      <div className="glass-panel rounded-2xl overflow-hidden shadow-sm border border-slate-200">
        <div className="overflow-x-auto">
          <table className="w-full text-left border-collapse">
            <thead>
              <tr className="bg-slate-50/50 border-b border-slate-100 text-xs uppercase tracking-wider text-slate-500">
                <th className="px-6 py-4 font-semibold">Status</th>
                <th className="px-6 py-4 font-semibold">Scan ID & Branch</th>
                <th className="px-6 py-4 font-semibold">Date & Duration</th>
                <th className="px-6 py-4 font-semibold">Issues</th>
                
                {/* Dynamic Columns based on Task Config */}
                {task.recordFields.map(field => (
                    <th key={field.key} className="px-6 py-4 font-semibold text-indigo-900/70 bg-indigo-50/30">
                        {field.label}
                    </th>
                ))}

                <th className="px-6 py-4 font-semibold text-right">Action</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-50 text-sm">
              {records.map(record => (
                <tr key={record.id} className="hover:bg-white/60 transition-colors group">
                  <td className="px-6 py-4">
                    <ScanStatusBadge status={record.status} />
                  </td>
                  <td className="px-6 py-4">
                    <div className="flex flex-col">
                        <span className="font-medium text-slate-800">{record.id}</span>
                        <span className="text-xs text-slate-400 flex items-center gap-1 mt-0.5">
                            <GitBranch className="w-3 h-3" /> {record.branch}
                        </span>
                    </div>
                  </td>
                  <td className="px-6 py-4">
                     <div className="flex flex-col text-slate-600">
                        <span className="flex items-center gap-1">
                            <Calendar className="w-3 h-3 text-slate-400"/> {new Date(record.startTime).toLocaleDateString()}
                        </span>
                        <span className="text-xs text-slate-400 mt-0.5">Duration: {record.duration}</span>
                     </div>
                  </td>
                  <td className="px-6 py-4">
                    <div className="flex gap-3">
                        <div className="flex flex-col">
                            <span className="text-lg font-bold text-slate-700">{record.totalIssues}</span>
                            <span className="text-[10px] text-slate-400 uppercase font-bold">Total</span>
                        </div>
                        <div className="w-px h-8 bg-slate-200"></div>
                        <div className="flex flex-col">
                            <span className="text-lg font-bold text-rose-500">{record.unconfirmedIssues}</span>
                            <span className="text-[10px] text-rose-400 uppercase font-bold">Pending</span>
                        </div>
                    </div>
                  </td>

                  {/* Dynamic Fields Data */}
                  {task.recordFields.map(field => (
                      <td key={field.key} className="px-6 py-4 text-slate-600 bg-slate-50/20">
                          {record.extensionData?.[field.key] || '-'}
                      </td>
                  ))}

                  <td className="px-6 py-4 text-right">
                    <Link 
                        to={`/record/${record.id}?type=${task.type}`}
                        className="inline-flex items-center px-3 py-1.5 border border-indigo-200 rounded-lg text-xs font-medium text-indigo-600 hover:bg-indigo-50 hover:border-indigo-300 transition-all"
                    >
                        View Report
                    </Link>
                  </td>
                </tr>
              ))}
              {records.length === 0 && (
                  <tr>
                      <td colSpan={5 + task.recordFields.length} className="px-6 py-12 text-center text-slate-400">
                          <div className="flex flex-col items-center gap-2">
                              <FileCode className="w-8 h-8 text-slate-300" />
                              <p>No scan records found. Start a scan to see results.</p>
                          </div>
                      </td>
                  </tr>
              )}
            </tbody>
          </table>
        </div>
        {/* Pagination Mock */}
        <div className="px-6 py-4 border-t border-slate-100 flex items-center justify-between">
            <span className="text-xs text-slate-400">Showing 1-5 of {records.length} records</span>
            <div className="flex gap-2">
                <button disabled className="px-3 py-1 rounded border border-slate-200 text-slate-300 text-xs">Previous</button>
                <button className="px-3 py-1 rounded border border-slate-200 text-slate-600 hover:bg-slate-50 text-xs">Next</button>
            </div>
        </div>
      </div>
    </div>
  );
};